package cn.yili12.business.controller;

import cn.yili12.business.cache.OnlineUserCache;
import cn.yili12.business.dto.*;
import cn.yili12.business.entity.MessageDb;
import cn.yili12.business.entity.UserDb;
import cn.yili12.business.service.MessageService;
import cn.yili12.business.service.UserService;
import cn.yili12.business.vo.Result;
import cn.yili12.common.thread.AgentThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Api(value = "用户操作")
@Slf4j
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private MessageService messageService;

    @Autowired
    private OnlineUserCache cache;

    @GetMapping("/listOrg")
    @ApiOperation("同一组用户列表")
    public Result listOrg(HttpServletRequest request) {
        UserDb userDb = (UserDb) AgentThreadLocal.get();
        List<UserDb> list = service.findByOrgId(userDb.getOrgId());
        List<OrgFriendDTO> friendList = list.stream()
                .filter(item -> !item.getId().equals(userDb.getId())) //过滤当前登录人
                .map(item -> {
                    OrgFriendDTO orgFriendDTO = new OrgFriendDTO(item);
                    orgFriendDTO.setStatus(cache.have(String.valueOf(item.getId())) ? 1 : 0);
                    return orgFriendDTO;
                })  //转换对象
                .collect(Collectors.toList()); //改为集合返回
        return Result.success("获取同机构所有用户成功", friendList);
    }

    @GetMapping("/friends")
    @ApiOperation("获取通信好友")
    public Result friends(HttpServletRequest request) {
        UserDb userDb = (UserDb) AgentThreadLocal.get();
        List<UserDb> list = service.findFriend(userDb.getId());
        List<LastFriendDTO> friendList = list.stream()
                .filter(item -> !item.getId().equals(userDb.getId())) //过滤当前登录人
                .map(item -> {
                    LastFriendDTO lastFriendDTO = new LastFriendDTO(item);
                    lastFriendDTO.setStatus(cache.have(String.valueOf(item.getId())) ? 1 : 0);
                    return lastFriendDTO;
                })  //转换对象
                .collect(Collectors.toList()); //改为集合返回
        return Result.success("获取通信好友", friendList);
    }


    @PostMapping("/addFriend")
    @ApiOperation("添加通信好友")
    public Result addFriend(@Valid FriendAddDTO friendAddDTO) {
        try {
            UserDb userDb = service.getById(Long.parseLong(friendAddDTO.getFriendId()));
            if (userDb == null) {
                return Result.fail("用户不存在");
            }
            service.saveOrUpdateFriend(Long.valueOf(friendAddDTO.getUserId()), Long.valueOf(friendAddDTO.getFriendId()));
            LastFriendDTO lastFriendDTO = new LastFriendDTO(userDb);
            return Result.success("添加通信好友成功", lastFriendDTO);
        } catch (Exception e) {
            log.error("添加朋友失败", e);
            return Result.fail("添加朋友失败");
        }
    }


    @PostMapping("/historyMsg")
    @ApiOperation("获取历史聊天记录")
    public Result historyMsg(
            @ApiParam(value = "当前页码", required = false) @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "当前页码", required = false) @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(value = "朋友编号", required = true) @RequestParam("friendId") Long friendId) {
        try {
            UserDb userDb = (UserDb) AgentThreadLocal.get();
            UserDb friend = service.getById(friendId);
            if (friend == null) {
                return Result.fail("好友不存在");
            }
            Page<MessageDb> history = messageService.findHistory(String.valueOf(userDb.getId()), String.valueOf(friendId), pageNo, pageSize);
            List<MessageDTO> list = history.getContent().stream().map(
                    item -> {
                        MessageDTO messageDTO = new MessageDTO(item);
                        if (messageDTO.getFromUser().equals(String.valueOf(userDb.getId()))) {
                            messageDTO.setFromUserName(userDb.getName());
                            messageDTO.setToUserName(friend.getName());
                        } else {
                            messageDTO.setFromUserName(friend.getName());
                            messageDTO.setToUserName(userDb.getName());
                        }
                        return messageDTO;
                    }).collect(Collectors.toList());

            list.sort(((o1, o2) -> {
                return o1.getSendTime().before(o2.getSendTime()) ? -1 : 1;
            }));
            PageInfo<MessageDTO> pageInfo = new PageInfo<>(history);
            pageInfo.setList(list);
            return Result.success("获取历史信息成功", pageInfo);
        } catch (Exception e) {
            log.error("获取聊天历史记录失败", e);
            return Result.fail("获取失败");
        }
    }

}
